<template>
    <div style="height:100%">
        <!-- 操作按钮区 -->
        <div class="tools">
            <el-button-group>
                <el-button type="primary" size="mini" @click="addCategory">增加类别</el-button>
                <el-button type="primary" size="mini" @click="addIndex">增加指标</el-button>
                <el-button type="primary" size="mini" @click="delSelect">删除选择</el-button>
            </el-button-group>
            <el-button-group>
                <el-button type="primary" size="mini" @click="jReset">自适应画布</el-button>
                <el-button type="primary" size="mini" @click="jCenter">居中</el-button>
                <el-button type="primary" size="mini" @click="jZoomIn">放大</el-button>
                <el-button type="primary" size="mini" @click="jZoomOut">缩小</el-button>
                <el-button type="primary" size="mini" @click="jExport">导出</el-button>
                <el-button type="primary" size="mini" @click="saveIndexConfig">保存配置</el-button>
                <el-button type="primary" size="mini" @click="returnIndexConfigList">返回列表</el-button>
            </el-button-group>
        </div>

        <!-- 树区 -->
        <!-- 'height:calc(100%)' -->
        <div style="display: flex;height:calc(100% - 20px)">
            <div style="flex:1" id="canvas-box">
                <canvas width="" height="" id="canvas"></canvas>
            </div>
            <div style="flex:0 0 300px">
                <div class="drawer-content">
                    <el-form :model="form" v-if="form.flag === 1">
                        <p>基本设置</p>
                        <el-form-item label="指标编码" :label-width="formLabelWidth">
                            <!-- 输入 -->
                            <el-input v-model="form.code" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="指标名称" :label-width="formLabelWidth">
                            <!-- 输入 -->
                            <el-input v-model="form.name" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="指标单位" :label-width="formLabelWidth">
                            <!-- 输入 -->
                            <el-input v-model="form.unit" autocomplete="off"></el-input>
                        </el-form-item>
                        <p>数据源设置</p>
                        <el-form-item label="分类" :label-width="formLabelWidth">
                            <!-- 分级选择器 -->
                            <el-cascader
                                    :show-all-levels="false"
                                    placeholder="请输入名称搜索"
                                    :options="treeData"
                                    v-model="form.dataCategoryItem"
                                    @change="handleDataChange"
                                    filterable>
                            </el-cascader>
                        </el-form-item>
                        <el-form-item label="关键指标" :label-width="formLabelWidth">
                            <!-- 多选 -->
                            <el-select v-model="form.dataFieldItem" placeholder="请选择关联字段">
                                <el-option
                                        v-for="item in dataFields"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <p>计算设置</p>
                        <el-form-item label="指标性质" :label-width="formLabelWidth">
                            <!-- 多选 -->
                            <el-select v-model="form.calModelItem" placeholder="请选择模型">
                                <el-option
                                        v-for="item in calModels"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                    <el-form :model="form" v-else>
                        <p>基本设置</p>
                        <el-form-item label="类别编码" :label-width="formLabelWidth">
                            <!-- 输入 -->
                            <el-input v-model="form.code" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="类别名称" :label-width="formLabelWidth">
                            <!-- 输入 -->
                            <el-input v-model="form.name" autocomplete="off"></el-input>
                        </el-form-item>
                        <el-form-item label="类别单位" :label-width="formLabelWidth">
                            <!-- 输入 -->
                            <el-input v-model="form.unit" autocomplete="off"></el-input>
                        </el-form-item>
                        <p>数据源设置</p>
                        <el-form-item label="分类" :label-width="formLabelWidth">
                            <!-- 分级选择器 -->
                            <el-cascader
                                    :show-all-levels="false"
                                    placeholder="请输入名称搜索"
                                    :options="treeData"
                                    v-model="form.dataCategoryItem"
                                    @change="handleDataChange"
                                    filterable>
                            </el-cascader>
                        </el-form-item>
                        <el-form-item label="关键类别" :label-width="formLabelWidth">
                            <!-- 多选 -->
                            <el-select v-model="form.dataFieldItem" placeholder="请选择关联字段">
                                <el-option
                                        v-for="item in dataFields"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                        <p>计算设置</p>
                        <el-form-item label="类别性质" :label-width="formLabelWidth">
                            <!-- 多选 -->
                            <el-select v-model="form.calModelItem" placeholder="请选择模型">
                                <el-option
                                        v-for="item in calModels"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
        </div>

    </div>
</template>

<script>
    import '../assets/js/jtopo-min.js'
    import IndexTree from '@/utils/indexTree'
    import env from '@/utils/env'

    const EVENT_CLICK_RETURN = "clickReturnEvent"

    export default {
        data() {
            return {
                wideTables: {},
                treeData: [],
                dataFields: [],
                calModels: [
                    {
                        value: '1',
                        label: '正向'
                    },
                    {
                        value: '2',
                        label: '负向'
                    },
                    {
                        value: '3',
                        label: '区间'
                    }
                ],
                form: {
                    dataCategoryItem: [],
                    dataFieldItem: '',
                    calModelItem: '1',
                    code: '',
                    name: '',
                    unit: '',
                    flag: 1
                },
                formLabelWidth: '80px',
                indexTree: null,
                apiUrl: '',
                caseId: 1,  //当前数据库max(case_id),
                isChange: false
            }
        },
        computed: {

            curSelectedTNode() {  //当前选中的节点
                if (this.indexTree) {
                    return this.indexTree.selectedNode
                } else {
                    return null;
                }
            },
            treeParams() {
                if(this.indexTree){
                    return JSON.stringify(this.indexTree.getPostParams())
                }else{
                    return null;
                }
            }
        },

        watch: {
            curSelectedTNode(newVal, oldVal) {  //监听节点变化
                if (oldVal) { //保存旧节点
                    let oldNode = oldVal
                    let tableId = this.form.dataCategoryItem[3]
                    oldNode.update1(this.form.name, this.form.code,
                        this.form.unit, this.wideTables[tableId].tableName,
                        [this.form.dataFieldItem], this.form.calModelItem)
                }
                if (newVal) {  //加载新节点
                    this.form.name = newVal.name
                    this.form.code = newVal.code
                    this.form.unit = newVal.unit
                    this.form.calModelItem = newVal.modelCode
                    this.form.flag = newVal.flag
                }
            },
            treeParams(newVal,oldVal) {
                if(newVal==='[]'|| oldVal==='[]'){
                    this.isChange = false
                }else{
                    this.isChange = true
                }
            }
        },

        methods: {

            saveIndexConfig() {
                //1、重新梳理节点树，更新level/sortIndex
                this.indexTree.reorderTreeNodes()
                //2、构造参数保存
                let fileData = new FormData();
                fileData.append("data", JSON.stringify(this.indexTree.getPostParams()))
                let that = this
                that.$axios.post(that.apiUrl + '/assessgovapp/api/saveIndexConfig/', fileData).then(function (response) {
                    that.$message({
                        showClose: true,
                        message: '保存配置成功',
                        type: 'success'
                    })
                    that.returnIndexConfigList()
                })
            },

            setCurIndex(row) {
                this.indexTree.projectId = row.id
                this.indexTree.headTitle = row.faname
                this.getIndexTreeNodes(row)
            },
            setCanvasWidth() {
                let box = document.querySelector("#canvas-box")
                let rect = box.getBoundingClientRect();
                const {width, height} = rect;
                let canvas = document.querySelector("#canvas");
                canvas.width = width;
                canvas.height = height;
            },

            getIndexTreeNodes(row) {  //通过方案Id获取指标树
                //从数据库中获取当前方案的指标配置树，如果没有，则添加一个新的根结点
                let that = this
                this.$axios.get(this.apiUrl + `/assessgovapp/api/indexConfig/list/item/?projectId=${row.id}`).then(res => {
                    let result = res.data.data
                    if (result.length > 0) {
                        //绘制根节点
                        for (let i = 0; i < result.length; i++) {
                            let r = result[i]
                            let isRoot = r.name == r.headTitle ? true : false
                            let tNode = that.indexTree.addTreeNode(r.caseId, r.name, r.flag, isRoot)
                            tNode.code = r.code
                            tNode.unit = r.unit
                            tNode.tableName = r.tableName
                            tNode.colNames = [r.columnName]
                            tNode.modelCode = r.modelCode

                            let parentNode = that.indexTree.findTreeNodeById(r.parentId)
                            if (parentNode) {
                                //添加连线
                                that.indexTree.addLink(parentNode, tNode)
                            }
                        }
                        that.indexTree.doLayout()
                    } else {
                        that.addCategory(row.faname)
                    }
                })
            },

            addCategory(faName) {   //新增类别
                if (!this.curSelectedTNode) {
                    this.indexTree.addTreeNode(this.caseId, faName, 0, true)
                } else {
                    let tNode1 = this.curSelectedTNode
                    if (tNode1.flag == 1) {
                        this.$message({
                            showClose: true,
                            message: '父节点为指标，后面不能添加类别',
                            type: 'error'
                        });
                        return
                    }
                    this.caseId++
                    let tNode2 = this.indexTree.addTreeNode(this.caseId, '', 0, false)
                    //添加连线
                    this.indexTree.addLink(tNode1, tNode2)
                    this.indexTree.doLayout()
                }
            },
            addIndex() {       //新增指标
                if (this.curSelectedTNode) {
                    this.caseId++
                    let tNode1 = this.curSelectedTNode
                    let tNode2 = this.indexTree.addTreeNode(this.caseId, '', 1)
                    //添加连线
                    this.indexTree.addLink(tNode1, tNode2)
                    this.indexTree.doLayout()
                }
            },

            delSelect() {   //删除选择
                if (this.curSelectedTNode.parentId == 0) {
                    this.$message({
                        showClose: true,
                        message: '根结点不能删除',
                        type: 'error'
                    });
                    return
                }
                this.$confirm('是否确认删除当前选中节点?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.indexTree.delSelect()
                }).catch(() => {

                });
            },

            jCenter() {    //居中
                this.indexTree.jCenter()
            },

            jZoomIn() {   //放大
                this.indexTree.jZoomIn()
            },

            jZoomOut() {   //缩小
                this.indexTree.jZoomOut()
            },

            jExport() {     //导出
                this.indexTree.jExport()
            },

            jReset() {   //自适应
                this.indexTree.doLayout()
                this.indexTree.jCenter()
            },

            dragCallback(msg) { //回调函数
                this.$message({
                    showClose: true,
                    message: msg,
                    type: 'error'
                });
            },

            handleDataChange(value) {
                //触发字段更新
                let that = this
                this.$axios.get(this.apiUrl + `/assessgovapp/api/data/fields/${value[3]}/`).then(res => {
                    that.dataFields = res.data.data
                    if (res.data.data.length > 0) {
                        that.form.dataFieldItem = res.data.data[0].value
                    }
                })
            },

            returnIndexConfigList() {
                if(this.isChange){
                    this.$confirm('返回列表会丢失修改，是否保存配置?', '提示', {
                        confirmButtonText: '保存',
                        cancelButtonText: '不保存',
                        type: 'confirm'
                    }).then(() => {
                        this.saveIndexConfig()
                        this.indexTree.resetIndexTree()
                        this.$emit(EVENT_CLICK_RETURN)
                    }).catch(() => {
                       console.log('不保存')
                        this.indexTree.resetIndexTree()
                        this.$emit(EVENT_CLICK_RETURN)
                    })
                }else{
                    this.indexTree.resetIndexTree()
                    this.$emit(EVENT_CLICK_RETURN)
                }

               
            },

            keyupSubmit() {
                let that = this
                document.onkeydown = e => {
                    debugger
                    if (e.target.type == "text" && e.target.tagName.toUpperCase() == "INPUT") return
                    let _key = window.event.key;//window.event.keyCode;
                    if (_key === 'Delete') { //绑定删除键
                        that.delSelect()
                    }
                    if(_key === 'Enter'){ //绑定回车键 添加新指标或新类别
                        if(that.curSelectedTNode){
                            if(that.curSelectedTNode.flag === 0) {//新增类别
                                that.addCategory()
                            }else{//新增指标
                                that.addIndex()
                            }
                        }
                    }
                }
            },

        },
        created() {
            console.log('trigger created')
            this.apiUrl = env.getApiUrl()
            let that = this
            this.$axios.get(this.apiUrl + '/assessgovapp/api/wideTable/list/').then(res => {
                that.wideTables = res.data.data
            })
            this.$axios.get(this.apiUrl + '/assessgovapp/api/indexTree/maxCaseId/').then(res => {
                that.caseId = res.data.data
            })

            this.keyupSubmit() //注册按键
        },
        mounted() {
            console.log('trigger mounted')
            let that = this
            this.$axios.get(this.apiUrl + '/assessgovapp/api/data/category/').then(res => {
                that.treeData = res.data.data
                if (res.data.data.length > 0) {
                    let r = res.data.data[0]
                    that.form.dataCategoryItem = [
                        r.value,
                        r.children[0].value,
                        r.children[0].children[0].value,
                        r.children[0].children[0].children[0].value]
                    that.handleDataChange(that.form.dataCategoryItem)
                }
            })

            //初始化指标树
            that.indexTree = new IndexTree("canvas", that.dragCallback)
        }
    }
</script>

<style lang="stylus" scoped>
    .tree-card
        height 100%

    .tools
        margin 0 0

        .el-button-group
            margin-right 15px

    .drawer-content
        padding 0 5px

        p
            margin 15px 0
            text-indent 10px

            &:first-child
                margin-top 0

        .save-btn
            width 100%
            margin-top 20px
</style>
